package com.shicijiaoliu.service.impl;

import com.github.pagehelper.PageHelper;
import com.shicijiaoliu.mapper.Sectionmapper;
import com.shicijiaoliu.pojo.Section;
import com.shicijiaoliu.service.Sectionservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class Sectionserviceimpl implements Sectionservice {

    @Autowired
    Sectionmapper sectionmapper;

    @Override
    public int getcount(String name,String createtime,String updatetime) {
        LocalDateTime stime = null;
        LocalDateTime etime = null;
        if(createtime != null){
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            stime = LocalDateTime.parse(createtime, fmt);
        }
        if(updatetime != null){
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            etime = LocalDateTime.parse(updatetime, fmt);
        }
        return sectionmapper.getcount(name,stime,etime);
    }

    @Override
    public void add(Section section) {
        sectionmapper.add(section);

    }

    @Override
    public List<Section> findBypage(int pagecount, int pagenumber, String name,String createtime,String updatetime) {
        LocalDateTime stime = null;
        LocalDateTime etime = null;
        if(createtime != null){
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            stime = LocalDateTime.parse(createtime, fmt);
        }
        if(updatetime != null){
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            etime = LocalDateTime.parse(updatetime, fmt);
        }
        int count = sectionmapper.getcount(null,null,null);
        int totalpage = (int) Math.ceil((double)count/pagenumber);
        if(pagecount>totalpage || pagecount <= 0){
            return null;
        }else{
            PageHelper.startPage(pagecount,pagenumber);
            return sectionmapper.findBypage(name,stime,etime);
        }
    }

    @Override
    public void update(Section section) {
        section.setUpdateTime(LocalDateTime.now());
        sectionmapper.update(section);

    }

    @Override
    public void delByid(long id) {
        sectionmapper.delByid(id);
    }

    @Override
    public Section findByid(long id) {
        return sectionmapper.findByid(id);
    }

    @Override
    public Section findByname(String name) {
        return sectionmapper.findByname(name);
    }
}
